const { sequelize, Sequelize } = require('../config/db.config.js');

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;

// 导入模型
db.User = require('./user.model.js')(sequelize, Sequelize);
db.Post = require('./post.model.js')(sequelize, Sequelize);
db.Comment = require('./comment.model.js')(sequelize, Sequelize);
db.Tag = require('./tag.model.js')(sequelize, Sequelize);

// 定义模型之间的关系
// 用户与文章的关系：一对多
db.User.hasMany(db.Post, { as: 'posts', foreignKey: 'userId' });
db.Post.belongsTo(db.User, { as: 'author', foreignKey: 'userId' });

// 文章与评论的关系：一对多
db.Post.hasMany(db.Comment, { as: 'comments', foreignKey: 'postId' });
db.Comment.belongsTo(db.Post, { as: 'post', foreignKey: 'postId' });

// 用户与评论的关系：一对多
db.User.hasMany(db.Comment, { as: 'comments', foreignKey: 'userId' });
db.Comment.belongsTo(db.User, { as: 'author', foreignKey: 'userId' });

// 文章与标签的关系：多对多
db.Post.belongsToMany(db.Tag, { through: 'Post_Tags', as: 'tags', foreignKey: 'postId' });
db.Tag.belongsToMany(db.Post, { through: 'Post_Tags', as: 'posts', foreignKey: 'tagId' });

module.exports = db;